#!/bin/bash

# 判断网络是否可用
function if_network() {
    ping -c 1 baidu.com > /dev/null 2>&1
    if [ $? -eq 0 ];then
        echo "检测网络正常"
    else
        echo "检测网络连接异常" && exit 1
    fi
}

function update_env() {
    # 替换阿里云
    yum install -y  wget
    mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bakup
    wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
    sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo
    yum clean all
    yum makecache
    yum install ca-certificates -y
    update-ca-trust extract
    # 安装常用依赖包
    yum install -y net-tools vim  git yum-utils make zlib zlib-devel gcc-c++ libtool openssl openssl-devel pcre pcre-devel gcc glibc cmake screen lrzsz tree dos2unix lsof tcpdump ntp setuptool psmisc openssl openssl-devel bind-utils traceroute epel-release bash-completion bash-completion-extras
    # 关闭swap
    swapoff -a
    sed -ri 's/.*swap.*/#&/' /etc/fstab
    free -h
    # 关闭selinux
    setenforce 0
    sed -ri 's/SELINUX=enforcing/SELINUX=disabled/'  /etc/selinux/config
    # 设置时区
    timedatectl set-timezone Asia/Shanghai
    # 时间同步
    /usr/sbin/ntpdate ntp1.aliyun.com
    crontab -l > crontab_conf ; echo "*/5 * * * * /usr/sbin/ntpdate ntp1.aliyun.com >/dev/null 2>&1" >> crontab_conf && crontab crontab_conf && rm -f crontab_conf
    # 关闭 firewalld
    systemctl stop firewalld
    systemctl disable firewalld
    echo "3秒钟后系统将会重启"
    sleep 3
    reboot
}

function update_network_name() {
    # 修改网卡名
    mv /etc/sysconfig/network-scripts/ifcfg-en* /etc/sysconfig/network-scripts/ifcfg-eth0
    cp /etc/sysconfig/network-scripts/ifcfg-eth0 /opt/ifcfg-eth0_bak
    sed -i -e "s/^NAME.*$/NAME=eth0/g"  -e 's/^DEVICE.*$/DEVICE=eth0/g' /etc/sysconfig/network-scripts/ifcfg-eth0
    sed -ri 's#rd.lvm.lv=centos/root rd.lvm.lv=centos/swap#rd.lvm.lv=centos/root net.ifnames=0 biosdevname=0 rd.lvm.lv=centos/swap#g' /etc/default/grub
    grub2-mkconfig -o /boot/grub2/grub.cfg
}

# 判断系统类型
function main() {
    os_type=$(grep 'PRETTY_NAME' /etc/os-release |awk -F '"' '{print $2}')
    if [[ $os_type =~ "CentOS" ]]; then
        if_network
        update_network_name
        update_env
    else
        echo "暂时不支持其他系统，后续待完善"
    fi
}

main
